package www.cslc.com.Util;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GsonDateTypeAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {
	private final String pattern = "yyyyMMddHHmmss";   
	@Override
	public JsonElement serialize(Date arg0, Type arg1,
			JsonSerializationContext arg2) {  
	        String dfString = DateFormatUtils.format(new Date(arg0.getTime()), pattern);      
			return new JsonPrimitive(dfString);  
	}

	@Override
	public Date deserialize(JsonElement arg0, Type arg1,
			JsonDeserializationContext arg2) throws JsonParseException {
		Date date = new Date();
		String str = arg0.getAsString();
		
		if (str == null || "".equals(str)) {
		    throw new JsonParseException(str);
		} else {
	          try {                   
	                
	                if (!Tools.checkNumFixedLength(str, 14) || !checkDateFormat(str)) {
	                    throw new JsonParseException(str);
	                }
	                
	                date = DateUtils.parseDate(str, pattern);
	            } catch (Exception e) {      
	                throw new JsonParseException(e);      
	            } 
		}
	
		return date;
	}
	
	/**
	 * @param src
	 * @return
	 */
	public static boolean checkDateFormat(String src){
		String reg = "((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))" +
        "|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))" +
        "|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229))" + 
        "(([0-1]?[0-9]|2[0-3])([0-5][0-9])([0-5][0-9]))";
		return Pattern.matches(reg, src);
	}

}
